#include "Common.h"
#include "Headers.h"
#include "AudioFile.h"
#include "WaveFile.h"





namespace Audio
{
	const INT ALL_IN_MEMORY_SIZE = 65536;

	AudioDataBuffer::AudioDataBuffer()
		:position(0)
		,currentBuffer(0)
	{
		for(unsigned int i = 0; i < numberOfbuffer; ++i)
		{
			buffer[i] = NULL;
			sizes[i] = 0;
		}
	}

	AudioDataBuffer::~AudioDataBuffer()
	{
		for(unsigned int i = 0; i < numberOfbuffer; ++i)
		{
			delete [] buffer[i];
			buffer[i] = NULL;
			sizes[i] = 0;
		}
	}

	unsigned char* AudioDataBuffer::GetNewBuffer(unsigned int size)
	{
		if(size > bufferLength)
			throw ArgumentOutOfRangeException();

		++currentBuffer;
		currentBuffer %= numberOfbuffer;
		if(buffer[currentBuffer] == NULL)
		{
			buffer[currentBuffer]= new unsigned char[size];
		}
		sizes[currentBuffer] = size;
		return buffer[currentBuffer];
	}

	unsigned char* AudioDataBuffer::GetCurrentBuffer()
	{
		return buffer[currentBuffer];
	}
	


	AudioVoice::AudioVoice(const String& file)		
		:waveFile(NULL)
		,fileName(file)
		,loaded(false)		
	{	
		waveFile  = new IO::WaveFile(fileName);
	}

	AudioVoice::~AudioVoice()
	{		
		while(!playings.empty())
		{
			AudioPlayingVoice* pv = playings.back();
			playings.pop_back();
			pv->Stop();
			AudioManager::Get()->DestoyAudioPlayingVoice(pv);
			
		}	
		delete waveFile;
	}	

	
	void AudioVoice::DeletePlayingVoice(AudioPlayingVoice* v)
	{
		std::vector<AudioPlayingVoice*>::iterator it = std::find(playings.begin(), playings.end(), v);
		if(it != playings.end())
		{
			playings.erase(it);
		}
		else
		{
			throw ArgumentException();
		}

	}
	void AudioVoice::AddPlayingVoice(AudioPlayingVoice* v)
	{
		playings.push_back(v);
	}	
	
	

	void AudioVoice::PreLoad()
	{		
		waveFile->Open();
		waveFile->LoadInfo();
	}

	AudioStream* AudioVoice::CreateAudioStream()
	{
		AudioStreamCreateParameter p = {0};
		p.File = waveFile;
		return AudioStream::Create(p);
	}

	void AudioVoice::DestroyAudioStream(AudioStream*& stream)
	{
		AudioStream::Destroy(stream);	
	}

	UINT32 AudioVoice::GetChannelCount() const
	{	
		return waveFile->GetChannelCount();
	}

	UINT32 AudioVoice::GetSampleRate() const
	{
		return waveFile->GetSampleRate();
	}
	UINT32 AudioVoice::GetBitsPerSample() const
	{		
		return waveFile->GetBitsPerSample();
	}

	UINT32 AudioVoice::GetSampleCount() const
	{		
		return waveFile->GetSampleCount();
	}


	void* AudioVoice::GetInfo() const
	{
		return waveFile->GetInfo();
	}
	UINT32 AudioVoice::GetInfoSize() const
	{
		return waveFile->GetInfoSize();
	}
	

}
